require 'net/http'

class ResourcesController < ApplicationController
  attr_reader :title
  attr_reader :resource_title
  attr_reader :resource
  def index
    list
    render :action => 'list'
  end

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @resource_pages, @resources = paginate :resources, :per_page => 10
  end

  def show
    @resource = Resource.find(params[:id])
  end

  def new
    @title = 'Post New Resource - DSL Forge'
    @resource = Resource.new
  end

  def validate_url_uniqueness
    @resource = Resource.new({:url => params[:resource_url]})
    @resource.valid?
    if @resource.errors.on("url") == nil
      render :layout => false , :action => 'validate_succeed'
    else
      render :layout => false , :action => 'url_unique_check_result'
    end
  end

  def create
    @resource = Resource.new(params[:resource])
    if @resource.save
      flash[:notice] = 'Resource was successfully created.'
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
  end

  def edit
    @resource = Resource.find(params[:id])
  end

  def update
    @resource = Resource.find(params[:id])
    if @resource.update_attributes(params[:resource])
      flash[:notice] = 'Resource was successfully updated.'
      redirect_to :action => 'show', :id => @resource
    else
      render :action => 'edit'
    end
  end
  
  def destroy
    Resource.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
  
  def get_resource_title
    @bad_link = false
    host, port, path = parse params[:resource_url]
    begin
      Net::HTTP.start host, port do |http|
        http.request_get path do |response|      
          raise 'bad link' unless response.code == '200'          
          @resource_title = title_in_html response if response['content-type'].include? 'text/html'
          break
        end
      end
    rescue
      @bad_link = true
    end   
    render :layout => false , :action => 'resource_title_loading_result'              
  end
  
  private
  def parse resource_url
    resource_url = "http://" + resource_url unless resource_url.include? 'http://'
    url = URI.parse resource_url
    [url.host, url.port, url.path == '' ? '/' : url.path]
  end

  private   
  def title_in_html response
    content = ''
    title = ''
    response.read_body do |segement|
      content += segement  
      start_index = content.index(/<[Tt][Ii][Tt][Ll][Ee]>/)
      end_index = content.index(/<\/[Tt][Ii][Tt][Ll][Ee]>/)   
      unless start_index == nil || end_index == nil
        title = content.slice(start_index + 7..end_index - 1)
        break
      end
    end
    title
  end
end